package com.zprmb.udzt;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.LogUtils;
import com.zprmb.udzt.util.VolleryUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


@SuppressLint("SetJavaScriptEnabled")
public class  Active_Webview extends BaseActivity {

	private ImageView iv_v4_web_back;
	private TextView tv_v4_web_title;
	private String title;
	private String ref = "";
	private String url;
	private WebView v4_webview;
	private RelativeLayout rl_back;
	private ProgressBar bar;
	private boolean back = false;
	private SharedPreferences sha;
	int flag;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.active_webview);
		BbtApplication.getInstance().addActvity(this);
		Intent intent = getIntent();
		title = intent.getStringExtra("title");
		url = intent.getStringExtra("url");
		ref = getShare().getString("usercode", "");

		Log.e("webview", url);
		// url = "account/invest/8F759CC2-65DB-11E5-AE96-5254002EAABD/contract";
		sha=getSharedPreferences("config", MODE_PRIVATE);
		initView();
		initData();
		 flag = getIntent().getIntExtra("flag", 0);
//		if (flag == 1) {
////			 v4_webview.loadUrl("http://192.168.40.154:8085/landing/mNationalDay2016?app=true");
//			// v4_webview.loadUrl(Constant.URL+"/h5/expIntro?app=true");
//
//			v4_webview.loadUrl(url);
//		} else {
//			v4_webview.loadUrl(Constant.URL+url);
//			// v4_webview.loadUrl("http://192.168.40.177:8085/landing/mWelfare8888-2016");
//		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		BbtApplication.getInstance().removeActvity(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// v4_webview.loadUrl("http://192.168.20.29:8080"+"/landing/reward?app=true&token="+getToken());
		if (flag == 1) {
//			 v4_webview.loadUrl("http://192.168.40.154:8085/landing/mNationalDay2016?app=true");
			// v4_webview.loadUrl(Constant.URL+"/h5/expIntro?app=true");
//v4_webview.loadUrl("file:///android_asset/Untitled1.html");
			v4_webview.loadUrl(url+"&token="+getToken());
		} else {
			v4_webview.loadUrl(Constant.URL+url+getToken());
			// v4_webview.loadUrl("http://192.168.40.177:8085/landing/mWelfare8888-2016");
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {

				Active_Webview.this.finish();
			
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void initData() {
		final Map<String, String> extraHeaders = new HashMap<String, String>();
		extraHeaders.put("token", getToken());
		v4_webview.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				if (url.indexOf("http://") == 0 || url.indexOf("https://") == 0) {
					

						back = true;
					
//                     Log.e("myurl", url+"");
					view.loadUrl(url);
					return true;
				}
				// else if(url.indexOf("tel")==0){
				// view.loadUrl(url,extraHeaders);
				// return true;
				// }
				// view.loadUrl(Constant.URL_NEW+url,extraHeaders);
				// view.loadUrl("http://docs.google.com/gview?embedded=true&url=http://www.navicat.com.cn/manual/pdf_manual/cn/navicat/rv_manual/rviewer_cs.pdf");
				return true;
			}

			public void onReceivedSslError(WebView view,
					SslErrorHandler handler, SslError error) {
				// super.onReceivedSslError(view, handler, error);
				handler.proceed();
			}

		});
		v4_webview.clearCache(true);
		v4_webview.setWebChromeClient(new WebChromeClient() {
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				Log.e("进度", newProgress + "");
				if (newProgress == 100) {
					bar.setVisibility(View.GONE);
				} else {
					if (View.INVISIBLE == bar.getVisibility()) {
						bar.setVisibility(View.VISIBLE);
					}
					bar.setProgress(newProgress);
				}
				super.onProgressChanged(view, newProgress);
			}

		});
		// 重新设置websettings WebSettings s = wb.getSettings();
		// s.setBuiltInZoomControls(true);
		// s.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		v4_webview.getSettings().setUseWideViewPort(true);
		v4_webview.getSettings().setLoadWithOverviewMode(true);
		v4_webview.getSettings().setSavePassword(true);
		v4_webview.getSettings().setSaveFormData(true);
		v4_webview.getSettings().setJavaScriptEnabled(true);
		// enable navigator.geolocation
		v4_webview.getSettings().setGeolocationEnabled(true);
		v4_webview.getSettings().setGeolocationDatabasePath(
				"/data/data/org.itri.html5webview/databases/");
		// enable Web Storage: localStorage, sessionStorage
//		v4_webview.getSettings().setDomStorageEnabled(true);
		v4_webview.requestFocus();
		v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		// v4_webview.setScrollBarStyle(0);
		String ua = v4_webview.getSettings().getUserAgentString();
		v4_webview.getSettings().setUserAgentString(
				ua + "; " + "rmbbox_android");
		v4_webview.addJavascriptInterface(new JsInterfaces(this),
				"AndroidWebView");
		v4_webview.getSettings().setBuiltInZoomControls(true);
		v4_webview.getSettings().setLayoutAlgorithm(
				WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		v4_webview.getSettings().setDomStorageEnabled(true);
		// Set cache size to 8 mb by default. should be more than enough
		v4_webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
		// This next one is crazy. It's the DEFAULT location for your app's
		// cache
		// But it didn't work for me without this line.
		// UPDATE: no hardcoded path. Thanks to Kevin Hawkins
		String appCachePath = getApplicationContext().getCacheDir()
				.getAbsolutePath();

		v4_webview.getSettings().setAllowFileAccess(true);
		v4_webview.getSettings().setAppCacheEnabled(true);
		v4_webview.getSettings().setJavaScriptEnabled(true);
		v4_webview.getSettings().setAppCachePath(appCachePath);
		v4_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		v4_webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
//		v4_webview.getSettings().setSupportZoom(true);
		v4_webview.getSettings().setDefaultTextEncodingName("utf-8");
		// v4_webview.loadUrl("http://preview.rmbbox.com:8082/v3/product/dqDescribe?flagFresh=false&type=FIXED_DEPOSIT_3");

		// if(title.equals("了解智投宝")){
		// v4_webview.loadUrl(Constant.URL+url);
		// }
		// else{
		// v4_webview.loadUrl(Constant.URL+url);
		// // v4_webview.loadUrl("http://192.168.2.12:8088/h5/help?app=true");
		// }
	}

	private class JsInterfaces {
		private Context mContext;

		public JsInterfaces(Context context) {
			this.mContext = context;
		}

		// 在js中调用window.AndroidWebView.showInfoFromJs(name)，便会触发此方法。
		@JavascriptInterface
		public void pleaseLogin(String name) {
			if (getShare().getString("mobile", "").equals("")) {
				Intent intent = new Intent(Active_Webview.this,
						Log_or_RegisActivity.class);				
				intent.putExtra("who", 3);
				startActivity(intent);
//				Active_Webview.this.finish();
			} else {
				Intent intent = new Intent(Active_Webview.this,
						LoginActivity.class);
					intent.putExtra("who", 3);				
				startActivity(intent);
//				Active_Webview.this.finish();
			}
  
		}
		@JavascriptInterface
		public void toproduct(String[] list) {
			
//			Toast.makeText(Active_Webview.this, list.toString(), 2000).show();
            
			Intent intent = new Intent(Active_Webview.this,
					DetailsActivity.class);
			intent.putExtra("flag", Boolean.parseBoolean( list[0]));					
			intent.putExtra("name", list[1]);
			intent.putExtra("type",  list[2]);
			intent.putExtra("id",  list[3]);
			intent.putExtra("isred", list[4]);
					
			
			startActivity(intent);
		}
		@JavascriptInterface
		public void refresh() {
			
//			Toast.makeText(Active_Webview.this, list.toString(), 2000).show();
            
			Intent intent = new Intent(Active_Webview.this,
					MainActivity.class);
			
					
			
			startActivity(intent);
		}
		@JavascriptInterface
		public void showInfoFromJs(String name) {

			initshare();
		}

		@JavascriptInterface
		public void switchpage(String name) {

			if (name.equals("red")) {
				Intent intent = new Intent(Active_Webview.this,
						MyHongBao.class);
				startActivity(intent);
			} else if (name.equals("exp")) {
				Intent intent = new Intent(Active_Webview.this,
						MyExperienceGold.class);
				startActivity(intent);
			}
		}

		@JavascriptInterface
		public void settab(int i) {

			Editor ed = sha.edit();
			ed.putInt("tab", i);
			ed.commit();
			Intent intent = new Intent(Active_Webview.this,
					MainActivity.class);
			intent.putExtra("licai", 1);
			startActivity(intent);
		}
		@JavascriptInterface
		public void setTitle(String title) {
			tv_v4_web_title.setText(title);
			
		}
		@JavascriptInterface
		public void setactivity(String activity) {

			
			Intent intent;
			try {
				intent = new Intent(Active_Webview.this,
						Class.forName(activity));
				startActivity(intent);
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		@JavascriptInterface
		public void addmoney(){
			verifuser("1");
		}

		public void sendInfoToJs(View view) {
			String msg = getToken();
			Log.e("web", "调用");
			// 调用js中的函数：showInfoFromJava(msg)

		}
	}

	private void initshare(){
		VolleryUtil volleryUtil=new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				LogUtils.e("invate", jsonObject.toString());
				if(jsonObject.optInt("success")==1){
					JSONObject json=jsonObject.optJSONObject("data");
					String linkurl="";
					if(ref.equals("")){
						linkurl= json.optString("linkUrl");
						
					}else{
						linkurl=  json.optString("linkUrl")+"?ref="+ref;
						
					}
					
					
					share(Active_Webview.this, json.optString("description"), json.optString("title"), linkurl, "");
				}else{
				 	
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};
		volleryUtil.setRequestMethod(0);
		volleryUtil.setShow(true);
		volleryUtil.execute(Active_Webview.this, Constant.URL+"/api/shareProductContent/inviteFriend/inviteFriend", "");
	}
	private void verifuser(final String who){
		VolleryUtil volleryUtil=new VolleryUtil() {
			
			@Override
			public void onUpDate(JSONObject jsonObject) {
				// TODO Auto-generated method stub
				if (jsonObject.optInt("success")==1) {
					JSONObject json = jsonObject.optJSONObject("data");
					
					if (json.optBoolean("nameAuth")&&json.optBoolean("isBindCard")) {
						if (who.equals("1")) {
//							
							Intent intent = new Intent(Active_Webview.this, V4AddMoneySActiviy.class);
							startActivity(intent);
						}else {
							if(json.optBoolean("payPass")){
								
								Intent intent = new Intent(Active_Webview.this, V4UpMoneyActivity.class);
								startActivity(intent);
							}else{
								Intent intent = new Intent(Active_Webview.this, Set_tr_pw.class);
								startActivity(intent);
							}
						}
					}else { 
						
//							if (!json.optBoolean("nameAuth")) {
//								Intent intent = new Intent(AssetsActivity.this,Real_Name.class);
//								startActivity(intent);
//								return;
//							}
						 if(json.optString("bankMobileStatus")!=null&&!json.optString("bankMobileStatus").equals("")&&json.optString("bankMobileStatus").equals("WAIT_CHECK")){
							 Intent intent = new Intent(Active_Webview.this,BankCardActivity.class);
								intent.putExtra("bankcard", json.optString("cardNo"));
								intent.putExtra("isbank", 1);
								intent.putExtra("logourl", json.optString("logoUrl"));
								intent.putExtra("banknameEn", json.optString("bankNameEn"));
								intent.putExtra("banknameCn", json.optString("bankNameCn"));
								intent.putExtra("status", json.optString("bankMobileStatus"));
								startActivity(intent);
								return;
						 }
							if (!json.optBoolean("isBindCard")) {
//								!json.optBoolean("isBindCard")
								Intent intent = new Intent(Active_Webview.this,BankCardActivity.class);
								intent.putExtra("who", 1);
								startActivity(intent);
								return;
							}
						
					}
				}else {
					if (jsonObject.optString("comment").equals("please login")) {
						Intent intent = new Intent(Active_Webview.this,LoginActivity.class);
						startActivity(intent);
					}
				}
			}
			
			@Override
			public void onError() {
				// TODO Auto-generated method stub
				
			}
		};
		volleryUtil.setRequestMethod(0);
		volleryUtil.setHeaders("token", getToken());
		volleryUtil.setShow(true);
		volleryUtil.execute(this, Constant.URL+"/api/v5/user/userInfo","");
	}
	private void initView() {
		iv_v4_web_back = (ImageView) findViewById(R.id.img_back);
		rl_back = (RelativeLayout) findViewById(R.id.rl_back);
		bar = (ProgressBar) findViewById(R.id.myProgressBar);
		rl_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			
					Active_Webview.this.finish();
				
			}
		});
		iv_v4_web_back.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				
					Active_Webview.this.finish();

				
			}
		});
		tv_v4_web_title = (TextView) findViewById(R.id.tv_v4_web_title);
		tv_v4_web_title.getPaint().setFakeBoldText(true);
		if (title.indexOf("了解") == 0) {
			tv_v4_web_title.setText("项目详情");
		} else {

			tv_v4_web_title.setText(title);
		}
		v4_webview = (WebView) findViewById(R.id.v4_webview);
	}
}
